package com.sc.VenusQueryBeta.global;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.Toast;

import com.hengjun.kingstar.sdk.global.GlobalApplication;
import com.hengjun.kingstar.sdk.utils.LanguageUtil;
import com.hengjun.kingstar.sdk.utils.LogUtil;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.hengjun.kingstar.sdk.widgets.DeviceIDUtil;
import com.sc.VenusQueryBeta.api.account.AccountApi;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.model.bean.account.DistanceloginBean;
import com.sc.VenusQueryBeta.model.bean.login.UsersLoginBean;
import com.sc.VenusQueryBeta.ui.activites.MainActivity;

import org.xutils.x;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.sc.VenusQueryBeta.api.Host.HostVGSestMessageserver;

/**
 * Created by SC-02 on 2018/9/18.
 * 程序入口
 */

public class MyApplication extends GlobalApplication {

    public static MyApplication app;//全局的上下文对象
    private UsersLoginBean loginBean;
    private long loginTime;
    private long loginOutTime;


    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (level == TRIM_MEMORY_UI_HIDDEN) {
            LogUtils.e("app进入后台运行" + new DeviceIDUtil(this).getDeviceUuid().toString().replaceAll("-", ""));
            SpUtils.putBoolean(MyApplication.app, Constants.ISBACKGROUND, true);
//            RxBus.rxBusUnbund(compositeDisposable);
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        initI18();
        JPushInterface.setDebugMode(false);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush
//        String packageName = context.getPackageName();
        // 获取当前进程名
//        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
//        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
//        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        // 初始化Bugly
//        CrashReport.initCrashReport(context, "129b986468", false, strategy);
        loginBean = SpUtils.getObject(app, UsersLoginBean.class);
        //初始化XUtils
        x.Ext.init(this);
        //设置debug模式
        x.Ext.setDebug(false);
        //关闭log
        LogUtils.setDebuggable(false);
//        LogUtil.
//        org.xutils.common.util.LogUtil
        LogUtil.e("deviceid=" + new DeviceIDUtil(app).getDeviceUuid().toString().replaceAll("-", ""));
        //設置極光別名
        JPushInterface.setAlias(this, 0, new DeviceIDUtil(app).getDeviceUuid().toString().replaceAll("-", ""));
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(final Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
            }

            @Override
            public void onActivityResumed(final Activity activity) {
//                LogUtil.e("前台与否："+isBackground(context));
                //登录过期
                LogUtils.e("进入前台");
                loginBean = SpUtils.getObject(app, UsersLoginBean.class);
                loginTime = SpUtils.getLong(MyApplication.app, Constants.LOGINTIME, 0);
                loginOutTime = SpUtils.getLong(MyApplication.app, Constants.LOGINTIMEOUT, 0);
                final long time = System.currentTimeMillis() / 1000;
                LogUtils.e("time=" + time);
                LogUtils.e("loginOutTime=" + loginOutTime);
                if (loginBean != null) {
                    if (loginOutTime != 0 && loginTime != 0) {
                        if (time >= loginOutTime) {
                            LogUtils.e("登录过期了");
                            SpUtils.clear(MyApplication.app);
                            SpUtils.putBoolean(MyApplication.app, Constants.OUT_DATE, true);
                            SpUtils.putString(MyApplication.app, Constants.PHONE, loginBean.getId());
                            SpUtils.putString(MyApplication.app, Constants.AREADECODE, loginBean.getAreaCode());
                            SpUtils.putBoolean(MyApplication.app, Constants.ISGUOQI, true);
                            int anInt1 = SpUtils.getInt(MyApplication.app, Constants.UNREAD_NUM, 0);
                            SpUtils.putInt(MyApplication.app, Constants.UNREAD_NUM, anInt1);
                            Intent intent = new Intent(activity, MainActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                            startActivity(intent);
                        }
                    } else {
                        LogUtils.e("已经退出登录了");
                    }
                }

                //异地登录
                loginBean = SpUtils.getObject(app, UsersLoginBean.class);
                if (loginBean != null) {
                    Constants.isForground = true;
//                //检查异地登录
                    Retrofit retrofit = new Retrofit.Builder().baseUrl(HostVGSestMessageserver) //设置域名
                            .addConverterFactory(GsonConverterFactory.create()) //添加数据解析器,需要添加对应依赖
                            .build();
//                    //通过Retrofit创建对应的请求服务
                    AccountApi apiService = retrofit.create(AccountApi.class);
//                    //对发送请求 进行封装
                    LogUtils.e("loginBean" + loginBean.getId() + loginBean.getDeviceUID() + loginBean.getToken());
                    Call<DistanceloginBean> catalogCall = apiService.distancelogin(loginBean.getId(),
                            new DeviceIDUtil(context).getDeviceUuid().toString().replaceAll("-", ""), loginBean.getToken());
                    //开始异步请求
                    if (SpUtils.getBoolean(MyApplication.app, Constants.DISTANCE_OUT1, true)) {//是異地
                        SpUtils.putBoolean(MyApplication.app, Constants.DISTANCE_OUT1, true);
                        catalogCall.enqueue(new Callback<DistanceloginBean>() {
                            @Override
                            public void onResponse(Call<DistanceloginBean> call, Response<DistanceloginBean> response) {
                                DistanceloginBean catalog = response.body();

                                if (catalog != null) {
                                    if (catalog.getReturnCode() == 107) {
                                        int anInt = SpUtils.getInt(MyApplication.app, Constants.NOTIFICATION_ID, 0);
//                                        LogUtil.e("int=" + anInt);
//                                        SpUtils.clear(MyApplication.app);
                                        SpUtils.putBoolean(MyApplication.app, Constants.DISTANCE_OUT1, false);
//                                        SpUtils.putBoolean(MyApplication.app, Constants.DISTANCE_OUT, true);//保存异地 标志
//                                        Intent intent2 = new Intent(context, MainActivity.class);
////                                        SpUtils.putInt(MyApplication.app,Constants.NOTIFICATION_ID,SpUtils.getInt(MyApplication.app,Constants.NOTIFICATION_ID,0));
//                                        intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                                        context.startActivity(intent2);

                                        LogUtil.e("175555");
                                        SpUtils.putBoolean(MyApplication.app, Constants.DISTANCE_OUT, true);//保存异地 标志
                                        Intent intent = new Intent(context, MainActivity.class);
                                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                        SpUtils.putInt(MyApplication.app, Constants.NOTIFICATION_ID, anInt);
                                        context.startActivity(intent);
//                                        SpUtils.clear(MyApplication.app);
//
                                        //11
//                                        AlertView alertView = new AlertView("警告", "你的账号正在异地登录！若不是本人操作，请修改密码", null, new String[]{"确定"}, null, activity, AlertView.Style.Alert, new OnItemClickListener() {
//                                            @Override
//                                            public void onItemClick(Object o, int position) {//
//                                                SpUtils.putBoolean(MyApplication.app, Constants.DISTANCE_OUT, true);//保存异地 标志
////                                                Intent intent = new Intent(activity, MainActivity.class);
////                                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
////                                                activity.startActivity(intent);
//
//                                                SpUtils.clear(MyApplication.app);
//                                                SpUtils.putBoolean(MyApplication.app, Constants.DISTANCE_OUT, true);//保存异地 标志
//                                                Intent intent2 = new Intent(context, MainActivity.class);
//                                                intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                                                context.startActivity(intent2);
//                                            }
//                                        });
//                                        alertView.setCancelable(false);
//                                        alertView.show();

                                        Log.d("tag", "是异地登录: " + catalog.getLoginTime());
                                    } else {
                                        LogUtils.e("sasa" + "不是异地");
                                    }
                                } else {
                                    LogUtils.e("catalog" + "==null");
                                }

                            }

                            @Override
                            public void onFailure(Call<DistanceloginBean> call, Throwable t) {
                                Toast.makeText(app, "onFailure: 失败" + t.getMessage(), Toast.LENGTH_SHORT).show();
                                Log.d("tag", "onFailure: 失败" + t.getMessage());
                            }
                        });
                    } else {

                    }

                } else {
                    LogUtils.e("login" + "=null");
                }
            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    /**
     * 初始化国际化语言，繁体字和简体字
     */
    private void initI18() {
        Resources resources = getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        if (LanguageUtil.getCountry(getApplicationContext()).equals("TW")) {
            config.locale = Locale.TAIWAN;
        } else {
            config.locale = Locale.CHINESE;
        }
        resources.updateConfiguration(config, dm);
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                /*
				BACKGROUND=400 EMPTY=500 FOREGROUND=100
				GONE=1000 PERCEPTIBLE=130 SERVICE=300 ISIBLE=200
				 */
                Log.i(context.getPackageName(), "此appimportace ="
                        + appProcess.importance
                        + ",context.getClass().getName()="
                        + context.getClass().getName());
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Log.i(context.getPackageName(), "处于后台"
                            + appProcess.processName);
                    return true;
                } else {
                    Log.i(context.getPackageName(), "处于前台"
                            + appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }

}
